package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchant.pojo.VerificatePo;
import cc.linker.steplink.crm.merchant.service.VerificateToolService;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchanth5.service.coupon.CouponH5Service;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 核销工具
 * @author huhj
 */

@RestController
@RequestMapping("/verificateTool")
public class VerificateToolController {

    @Autowired
    private UserInfoUtil userInfoUtil;

    @Autowired
    private VerificateToolService verificateToolService;

    @Autowired
    private RequestFilter requestFilter;

    @Autowired
    private CouponH5Service couponH5Service;

    /**
     * 获取列表
     * @param request
     * @return
     */
    @GetMapping("/getlist")
    public Object getlist(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            String couponName,String verificateId, String startTime, String endTime,Integer couponType,Integer couponSource,String verificateUserName,
            HttpServletRequest request)  throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        if(userinfo.getSaler()){
            customerId = userinfo.getCustomerId();
        }
        if (!StringUtils.isEmpty(couponName)) {
            couponName = URLDecoder.decode(couponName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            couponName = couponName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(verificateUserName)) {
            verificateUserName = URLDecoder.decode(verificateUserName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            verificateUserName = verificateUserName.replaceAll("%", "/%");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("couponName", couponName);
        params.put("verificateId", verificateId);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("couponType", couponType);
        params.put("couponSource", couponSource);
        params.put("verificateUserName", verificateUserName);
        params.put("orgId", orgId);
        params.put("customerId", customerId);
        PageHelper.startPage(pageIndex, pageSize);
        return  new PageInfo<>(verificateToolService.getList(params));
    }


    /**
     * 导出列表
     * @param request
     * @return
     */
    @GetMapping("/exportlist")
    public void exportlist(
            String couponName,String verificateId, String startTime, String endTime,Integer couponType,Integer couponSource,String verificateUserName,
            HttpServletRequest request, HttpServletResponse response)  throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        if(userinfo.getSaler()){
            customerId = userinfo.getCustomerId();
        }
        if (!StringUtils.isEmpty(couponName)) {
            couponName = URLDecoder.decode(couponName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            couponName = couponName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(verificateUserName)) {
            verificateUserName = URLDecoder.decode(verificateUserName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            verificateUserName = verificateUserName.replaceAll("%", "/%");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("couponName", couponName);
        params.put("verificateId", verificateId);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("couponType", couponType);
        params.put("couponSource", couponSource);
        params.put("verificateUserName", verificateUserName);
        params.put("orgId", orgId);
        params.put("customerId", customerId);
        verificateToolService.exportlist(params,response);
    }

    /**
     * 恢复可用
     * @param ： id  主键id
     * @return
     */
    @PostMapping("/recovery")
    public void recovery(@RequestBody Map<String, Object> params){
        verificateToolService.recovery(params);
    }

    /**
     * 根据核销号查询优惠券
     * @param ： verificateId  核销号
     * @return
     */
    @GetMapping("/getCouponByVerificateId")
    public Object getCouponByVerificateId(String verificateId, HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String customerId = userinfo.getSaler() ? userinfo.getCustomerId() : userinfo.getOrgId();
        CouponCustomerInfo couponCustomerInfo = CouponCustomerInfo
                .builder()
                .customerId(userinfo.getSaler() ? userinfo.getCustomerId() : userinfo.getOrgId())
                .customerName(userinfo.getAdminName())
                .customerPhone(userinfo.getSaler() ? userinfo.getBindPhone() : "")
                .cover("")
                .orgId(userinfo.getOrgId())
                .build();

        Map map = new HashMap();
        map.put("consumptionId",verificateId);
        Map<String, Object> couponMap = couponH5Service.getCouponDetail(map, couponCustomerInfo);
        String createCustomerId = "";
        if(!StringUtils.isEmpty(couponMap.get("createCustomerId"))){
            createCustomerId = couponMap.get("createCustomerId").toString();
        }
        if(couponMap==null || couponMap.size()==0){
            throw GlobalException.build("没有找到对应卡券");
        }else if(!createCustomerId.equals(customerId)){
            throw GlobalException.build("没有找到对应卡券");
        }
        couponMap.put("isYzjCoupon",0);
        return couponMap;
    }


    /**
     * pc核销
     * @param ： verificateId  核销号
     * @return
     */
    @PostMapping("/consume")
    public void consume(@RequestBody Map<String, Object> params, HttpServletRequest request){
        //判断该优惠券是否已被核销
        int count = verificateToolService.getVerificateCount(params);
        if(count>0){
            throw GlobalException.build("核销失败，该卡券已被核销");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        CouponCustomerInfo couponCustomerInfo = CouponCustomerInfo
                .builder()
                .customerId(userinfo.getSaler() ? userinfo.getCustomerId() : userinfo.getOrgId())
                .customerName(userinfo.getAdminName())
                .customerPhone(userinfo.getSaler() ? userinfo.getBindPhone() : "")
                .cover("")
                .orgId(userinfo.getOrgId())
                .build();
        Integer isYzjCoupon = 0;
        if(!StringUtils.isEmpty(params.get("isYzjCoupon"))){
            isYzjCoupon = Integer.valueOf(params.get("isYzjCoupon").toString());
        }
        //消核
        couponH5Service.useCustomerCoupon(params.get("verificateId").toString(),isYzjCoupon,couponCustomerInfo,null, userinfo.getOrgId());
    }



    /**
     * 获取核销员列表
     * @param request
     * @return
     */
    @GetMapping("/getVerificaterlist")
    public Object getVerificaterlist(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                     @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                     String name,Integer status,
                                     HttpServletRequest request)  throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        if(userinfo.getSaler()){
            customerId = userinfo.getCustomerId();
        }
        if (!StringUtils.isEmpty(name)) {
            name = URLDecoder.decode(name.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            name = name.replaceAll("%", "/%");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("status", status);
        params.put("orgId", orgId);
        params.put("customerId", customerId);
        PageHelper.startPage(pageIndex, pageSize);
        return  new PageInfo<>(verificateToolService.getVerificaterlist(params));
    }

    /**
     * 删除核销员
     * @param ： id  主键id
     * @return
     */
    @PostMapping("/deleteVerificater")
    public void deleteVerificater(@RequestBody Map<String, Object> params){
        verificateToolService.deleteVerificater(params);
    }

    /**
     * 通过核销员
     * @param ： id  主键id
     * @return
     */
    @PostMapping("/passVerificater")
    public void passVerificater(@RequestBody Map<String, Object> params){
        verificateToolService.passVerificater(params);
    }
}
